<template>
  <div :style="newStyle">
    <span v-if="$attrs.onlyShow">{{modelValue}}</span>
    <el-autocomplete
      v-else
      v-model="formValue"
      v-bind="$attrs"
      :fetch-suggestions="querySearch"
      style="width:100%"
      @input="onInput"
      @blur="onBlur"
      @focus="onFocus"
      @change="onChange"
      @clear="onClear"
    >
      <template
        slot="prepend"
        v-if="$attrs.__slot__ && $attrs.__slot__.prepend"
      >{{ $attrs.__slot__.prepend }}</template>
      <template slot="append" v-if="$attrs.__slot__ && $attrs.__slot__.append">
        {{
        $attrs.__slot__.append
        }}
      </template>
      <template slot-scope="{ item }">
        <div>{{ item[dataObj.props.value] }}</div>
      </template>
    </el-autocomplete>
  </div>
</template>

<script>
import { comMixin } from "../../../utils/comMixins";
export default {
  mixins: [comMixin],
  name: "form-autocomplete",
  model: {
    prop: "modelValue", // 绑定的值，通过父组件传递
    event: "update",
  },
  props: {
    modelValue: {
      type: [String, Number],
      default: "",
    },
  },

  computed: {
    formValue: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit("update:modelValue", val);
      },
    },
  },
  methods: {
    querySearch(queryString, cb) {
      const results = queryString
        ? this.resData.filter(this.createFilter(queryString))
        : this.resData;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant[this.dataObj.props.value]
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
  },
};
</script>

<style lang="scss" scoped></style>
